package com.example.demo.controller;

import com.example.demo.common.OkHttpUtils;
import com.example.demo.common.PropertyUtil;
import com.example.demo.common.SessionAndGetRemote;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping(value = "goImage")
public class GoImageController {
    private static final Logger logger = LoggerFactory.getLogger(GoImageController.class);

    private static String BACKURL = PropertyUtil.getValue("backurl");

    @Autowired
    private OkHttpUtils okHttpUtils;

    /**
     * @Description 初始化界面 查看是否存有session 并获取所有门店
     * @Author zhangxue
     * @Date 16:29 2018/7/11
     * @Param
     * @retrun
     **/
    @RequestMapping(value="/initImgPage",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String initPage(HttpSession session){
        String username = session.getAttribute("username")!=null?session.getAttribute("username").toString():null;
        String Store = session.getAttribute("store")!=null?session.getAttribute("store").toString():null;
        String userno = session.getAttribute("userno")!=null?session.getAttribute("userno").toString():null;
        String bm = session.getAttribute("bm")!=null?session.getAttribute("bm").toString():null;
        Map<String,Object> tMap = new HashMap<>();
        tMap.put("username",username);
        tMap.put("store",Store);
        tMap.put("userno",userno);
        tMap.put("bm",bm);
        JSONObject js = new JSONObject();
        if(username==null||Store==null){
            tMap.put("status","0");
            js = JSONObject.fromObject(tMap);
            return js.toString();
        }else{
            JSONObject jsonObject = JSONObject.fromObject(tMap);
            Map<String,String> headersParams = new HashMap<String,String>();
            headersParams.put("Content-Type","application/json;UTF-8");
            Map<String,Object> statusMap = okHttpUtils.sendPostJson(BACKURL+"/initImgPage",headersParams,jsonObject.toString(),new Object());
            statusMap.put("status","1");
            statusMap.put("store",Store);
            statusMap.put("username",username);
            statusMap.put("userno",userno);
            statusMap.put("bm",bm);
            js = JSONObject.fromObject(statusMap);
            return js.toString();
        }
    }

    @RequestMapping(value="/changeFactory",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String changeFactory(@RequestBody Map<String,Object> param){
        String url = BACKURL+"/changeFactory";
        Map<String,Object> statusMap = SessionAndGetRemote.getRemoteResult(param,url,okHttpUtils);
        String data = statusMap.get("data")!=null?statusMap.get("data").toString():null;
        return data;
    }

    @RequestMapping(value="/changeProduct",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String changeProduct(@RequestBody Map<String,Object> param){
        String url = BACKURL+"/changeProduct";
        Map<String,Object> statusMap = SessionAndGetRemote.getRemoteResult(param,url,okHttpUtils);
        String data = statusMap.get("data")!=null?statusMap.get("data").toString():null;
        return data;
    }

    /**
         * @Description 通过厂家和产品查询所有图片
         * @Author zhangxue
         * @Date 16:16 2018/8/23
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/queryImagesByFIDAndPID",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryImagesByFIDAndPID(@RequestBody Map<String,Object> param){
        String url = BACKURL+"/queryImagesByFIDAndPID";
        Map<String,Object> statusMap = SessionAndGetRemote.getRemoteResult(param,url,okHttpUtils);
        String data = statusMap.get("data")!=null?statusMap.get("data").toString():null;
        return data;
    }

    /**
     * @Description 上传图片
     * @Author zhangxue
     * @Date 18:08 2018/7/12
     * @Param
     * @retrun
     **/
    @ResponseBody
    @RequestMapping(value = "/uploadImage")
    public String uploadImage(@RequestParam(value = "file", required = true) MultipartFile[] file, @RequestParam(value="FID")String FID,@RequestParam(value="PID")String PID, HttpServletRequest request) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        String oldName = "";
        String fpath = "";
        // 定义允许上传的文件扩展名

        try {
            //如果文件不为空，写入上传路径
            if(!file[0].isEmpty()) {
                //上传文件路径
                // 得到上传文件的扩展名
                String fileExt = file[0]
                        .getOriginalFilename()
                        .substring(
                                file[0].getOriginalFilename()
                                        .lastIndexOf(".") + 1)
                        .toLowerCase();
                String fileName = UUID.randomUUID().toString()
                        .replaceAll("-", "")
                        + "_" + FID+"_"+PID + "." + fileExt;
                fpath = request.getScheme() + "://"
                        + request.getServerName() + ":"
                        + request.getServerPort()
                        + request.getContextPath() + "/"
                        + "uploadimg/"+FID+"/"+PID+"/" + fileName;
                String path = request.getSession().getServletContext().getRealPath("/")
                        + "uploadimg/"  + "/";
                //上传文件名
                oldName = file[0].getOriginalFilename();
                File filepath = new File(path+FID+"/"+PID+"/"+fileName);
                //判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }
                //将上传文件压缩后保存到一个目标文件当中
                file[0].transferTo(new File(path +FID+"/"+PID+"/"+ fileName));
                Map<String, Object> param = new HashMap<>();
                param.put("FID", FID);
                param.put("PID", PID);
                param.put("fileurl", fpath);
                param.put("IName", fileName);
                String url = BACKURL+"/uploadImage";
                Map<String,Object> statusMap = SessionAndGetRemote.getRemoteResult(param,url,okHttpUtils);
                String data = statusMap.get("data")!=null?statusMap.get("data").toString():null;
                return data;
            } else {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Description 通过风格和品类查询所有图片
     * @Author zhangxue
     * @Date 16:16 2018/8/23
     * @Param
     * @retrun
     **/
    @RequestMapping(value="/queryAllImageByStyleAndType",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryAllImageByStyleAndType(@RequestBody Map<String,Object> param){
        String url = BACKURL+"/queryAllImageByStyleAndType";
        Map<String,Object> statusMap = SessionAndGetRemote.getRemoteResult(param,url,okHttpUtils);
        String data = statusMap.get("data")!=null?statusMap.get("data").toString():null;
        return data;
    }

    /**
         * @Description 通过ID删除图片
         * @Author zhangxue
         * @Date 15:14 2018/8/24
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/delectImageByID",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String delectImageByID(@RequestBody Map<String,Object> param,HttpServletRequest request){
        String url = BACKURL+"/delectImageByID";
        Map<String,Object> statusMap = SessionAndGetRemote.getRemoteResult(param,url,okHttpUtils);
        String data = statusMap.get("data")!=null?statusMap.get("data").toString():null;
        String path = request.getSession().getServletContext().getRealPath("/")
                + "uploadimg/"  + "/";
        String FID = param.get("FID")!=null?param.get("FID").toString():null;
        String PID = param.get("PID")!=null?param.get("PID").toString():null;
        String FileName = param.get("IName")!=null?param.get("IName").toString():null;
        String FilePath = path+FID+"/"+PID+"/"+FileName;
        File delFile = new File(FilePath);
        if(delFile.exists()){
            delFile.delete();
        }
        return data;
    }

}
